<?php

namespace app\api\controller\v1;

use wheat\Wheat;

/**
 * 2019-07-02
 * 去除接口返回的麦位信息
 * Class Order
 * @package app\api\controller\v1
 */
class Order extends \app\api\controller\Order
{

    
    /**
     * 上麦、换麦、抱麦
     * */
    public function upWheat(){

        $post = request()->only(['wheat_id','type','user_id'],'post');
        //验证数据
        $result = $this->validate($post,'Wheat.up');
        if(true !== $result){
            api_return(0,$result);
        }

        if(!empty($post['user_id'])){
            $user_id = dehashid($post['user_id']);
            if (!is_numeric($user_id)) api_return(0,'参数错误');
        }else{
            $user_id = $this->user_id;
        }

        $wheat = new Wheat();
        if(isset($post['type']) && $post['type']  == 1){//抱麦

            $this->checkPower($this->user_id);

            if ($post['wheat_id'] == 1){
                api_return(0,'接待位不能抱麦');
            }

            $ret = $wheat->embrace($post['user_id'],self::$room_id,$post['wheat_id'],getPowerCode($post['user_id'],self::$room_id));
        }else{//上麦

            $powerCode = $this->getPowerCode();

//            switch ($powerCode){
//                case 1:
//                    api_return(0,'房主不能上其它麦位');
//                    break;
//                case 2:
//                case 3:
//                    if ($post['wheat_id'] == 1){
//                        api_return(0,'房主位不能上麦');
//                    }
//                    break;
//                default:
                    if (self::$is_free){
                        if (in_array($post['wheat_id'],self::$generalNotUp)){
                            if (!$powerCode){
                                api_return(0,'非管理员不能上麦');
                            }
                        }
                    }else{
                        if ($post['wheat_id'] != 9){
                            api_return(0,'观众只能上老板位,其它麦位需申请');
                        }
                    }
//                    break;
//            }
            $ret = $wheat->on($this->user_id,self::$room_id,$post['wheat_id'],getPowerCode($this->user_id,self::$room_id));
        }
        if($ret['code']){

            //用户上麦成功 且在排麦中 清除排麦数据
            $type = $post['wheat_id'] == 9 ?1:2;
            $rows = cache($type.'wheatRequest_'.self::$room_id)??[];
            if (in_array($user_id,$rows)){
                unset($rows[$user_id]);
                if(is_array($rows)){
                    $num = count($rows);
                }else{
                    $num = 0;
                }
                cache($type.'wheatRequest_'.self::$room_id,$rows,todayEndTime());
                $this->sendRoomMsg(self::$room_id,'wheatRequest'.$type,['num'=>$num,'type'=>2,'user_id'=>hashid($user_id)]);
            }
            $this->refreshWheat(self::$room_id);

            api_return(1,$ret['msg']);


        }else{
            api_return(0,$ret['msg']);
        }
    }




}